package com.yss.reportworld.service.impl;

import java.sql.Connection;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yss.common.core.constant.RequestDataHelper;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.reportworld.enums.ReportWorldEnum;
import com.yss.reportworld.service.IDatabaseCheckService;
import com.yss.reportworld.util.TableInfoUtil;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.stereotype.Service;
import com.yss.reportworld.service.ITableIndexedService;
import com.yss.reportworld.mapper.TableIndexedMapper;
import com.yss.reportworld.domain.TableIndexed;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;

/**
 * 对应索引信息Service业务层处理
 *
 * @author yss
 * @date 2023-03-30
 */
@Slf4j
@Service
public class TableIndexedServiceImpl extends ServiceImpl<TableIndexedMapper, TableIndexed> implements ITableIndexedService {
    @Autowired
    private IDatabaseCheckService databaseCheckService;
    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    /**
     * 查询对应索引信息列表
     *
     * @param tableIndexed 对应索引信息
     * @return 对应索引信息
     */
    @Override
    public List<TableIndexed> selectTableIndexedList(TableIndexed tableIndexed) {
        try {
            TableInfoUtil.handleTableVersion(tableIndexed.getHisVersion()); // 替换表名
            QueryWrapper<TableIndexed> wrapper = new QueryWrapper();
            wrapper.orderByDesc("STATUS");
            wrapper.orderByAsc("INDEXED_SEQUENCE");
            wrapper.orderByAsc("INDEXED_COLUMN_SEQUENCE");
            if (StringUtils.isNotEmpty(tableIndexed.getTableId())) {
                wrapper.eq("TABLE_ID", tableIndexed.getTableId());
            }
            if (StringUtils.isNotEmpty(tableIndexed.getIndexedName())) {
                wrapper.like("INDEXED_NAME", tableIndexed.getIndexedName());
            }
            if (StringUtils.isNotEmpty(tableIndexed.getIndexedColumnName())) {
                wrapper.like("INDEXED_COLUMN_NAME", tableIndexed.getIndexedColumnName());
            }
            if (StringUtils.isNotEmpty(tableIndexed.getIndexedAscDesc())) {
                wrapper.eq("INDEXED_ASC_DESC", tableIndexed.getIndexedAscDesc());
            }
            return this.list(wrapper);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }


    /**
     * 获取 索引信息
     *
     * @param tableIndexed
     * @return
     */
    public TableIndexed selectTableIndexedById(TableIndexed tableIndexed) {
        try {
            if (StringUtils.isEmpty(tableIndexed.getId())) {
                throw new BusinessException("没有获取到表索引信息！");
            }
            TableInfoUtil.handleTableVersion(tableIndexed.getHisVersion()); // 替换表名
            TableIndexed tableInfo = this.getById(tableIndexed.getId());
            if (StringUtils.isNull(tableInfo)) {
                return null;
            }
            return tableInfo;
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }


    @Transactional
    public void addTableIndexed(TableIndexed tableIndexed) {
        try {
            TableInfoUtil.handleTableVersion(tableIndexed.getHisVersion()); // 替换表名
            tableIndexed.setId(IdUtils.fastSimpleUUID());
            tableIndexed.setCreateBy(SecurityUtils.getUsername());
            tableIndexed.setCreateTime(new Date());
            this.save(tableIndexed);
            ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
            Connection connection = holder.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            String msgInfo = databaseCheckService.checkDataBaseAllByCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getDesc(), connection, "");
            if (StringUtils.isNotEmpty(msgInfo)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException(msgInfo);
            }
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    @Transactional
    public void etidTableIndexed(TableIndexed tableIndexed) {
        try {
            TableInfoUtil.handleTableVersion(tableIndexed.getHisVersion()); // 替换表名
            tableIndexed.setUpdateTime(new Date());
            tableIndexed.setUpdateBy(SecurityUtils.getUsername());
            this.updateById(tableIndexed);
            ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
            Connection connection = holder.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            String msgInfo = databaseCheckService.checkDataBaseAllByCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getDesc(), connection, "");
            if (StringUtils.isNotEmpty(msgInfo)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException(msgInfo);
            }
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 删除索引信息
     *
     * @param tableIndexed
     */
    public void delTableIndexed(TableIndexed tableIndexed) {
        try {
            TableInfoUtil.handleTableVersion(tableIndexed.getHisVersion()); // 替换表名
            if (StringUtils.isEmpty(tableIndexed.getIdList())) {
                throw new BusinessException("没有获取到删除数据的信息，请稍后重试！");
            }
            this.removeByIds(tableIndexed.getIdList());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 校验表索引唯一信息
     *
     * @param tableIndexed
     * @return 结果
     */
    @Override
    public boolean checkTableIndexedUnique(TableIndexed tableIndexed) {
        try {
            TableInfoUtil.handleTableVersion(tableIndexed.getHisVersion()); // 替换表名
            String tableIndexedId = StringUtils.isNull(tableIndexed.getId()) ? "-1" : tableIndexed.getId();
            QueryWrapper<TableIndexed> wrapper = new QueryWrapper<>();
            wrapper.eq("TABLE_ID", tableIndexed.getTableId());
            wrapper.eq("INDEXED_NAME", tableIndexed.getIndexedName());
            wrapper.eq("INDEXED_COLUMN_NAME", tableIndexed.getIndexedColumnName());
            TableIndexed info = this.getOne(wrapper);
            if (StringUtils.isNotNull(info) && !info.getId().equals(tableIndexedId)) {
                return false;
            }
            return true;
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 获取所有表索引信息信息
     *
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, List<TableIndexed>> getTableIndexedMap(boolean isNormal) {
        // 索引信息
        QueryWrapper<TableIndexed> tableIndexedQueryWrapper = new QueryWrapper<>();
        if (!isNormal) {
            tableIndexedQueryWrapper.in("STATUS", YssStatusEnum.getUpgradeToolsZipStatus());
        } else {
            tableIndexedQueryWrapper.eq("STATUS", YssStatusEnum.NORMAL.getCode());
        }
        tableIndexedQueryWrapper.orderByAsc("INDEXED_SEQUENCE,INDEXED_COLUMN_SEQUENCE");
        List<TableIndexed> tableIndexedList = this.list(tableIndexedQueryWrapper);
        if (CollectionUtils.isEmpty(tableIndexedList)) {
            log.error("没有获取到索引信息！");
            return null;
        }
        return this.getIndexedListMap(tableIndexedList);
    }


    /**
     * 获取所有表索引信息信息
     *
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, List<TableIndexed>> getTableIndexedMapByZip() {
        // 索引信息
        QueryWrapper<TableIndexed> tableIndexedQueryWrapper = new QueryWrapper<>();
        tableIndexedQueryWrapper.in("STATUS", YssStatusEnum.getUpgradeToolsZipStatus());
        tableIndexedQueryWrapper.orderByAsc("INDEXED_SEQUENCE,INDEXED_COLUMN_SEQUENCE");
        List<TableIndexed> tableIndexedList = this.list(tableIndexedQueryWrapper);
        if (CollectionUtils.isEmpty(tableIndexedList)) {
            log.error("没有获取到索引信息！");
            return null;
        }
        // 索引处理
        return this.getIndexedListMap(tableIndexedList);
    }

    private Map<String, List<TableIndexed>> getIndexedListMap(List<TableIndexed> tableIndexedList) {
        // 索引处理
        Map<String, List<TableIndexed>> mapTableIndexed = new LinkedHashMap<>();
        for (TableIndexed indexed : tableIndexedList) {
            if (StringUtils.isNull(indexed) || StringUtils.isBlank(indexed.getTableId())) {
                continue;
            }
            if (mapTableIndexed.containsKey(indexed.getTableId())) {
                List<TableIndexed> list = mapTableIndexed.get(indexed.getTableId());
                list.add(indexed);
                mapTableIndexed.put(indexed.getTableId(), list);
            } else {
                List<TableIndexed> list = new ArrayList<>();
                list.add(indexed);
                mapTableIndexed.put(indexed.getTableId(), list);
            }
        }
        return mapTableIndexed;
    }

}
